package com.skyworth.plugin.parser.jni;

import android.content.Context;
import android.os.RemoteException;

import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.skyworth.badsdk.SkyDownloadListener;
import com.skyworth.badsdk.SkyHttpDownloader;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.framework.skysdk.android.SkySystemUtil.LINUX_CMD;
import com.skyworth.framework.skysdk.util.MD5Util;
import com.skyworth.webSDK.webservice.tcappstore.SoFileBean;

import java.io.File;

public class DownloadPlayerPlugin implements SkyDownloadListener {
    private static Context mContext = null;
    private static DownloadPlayerPlugin instance;
    private final static String pluginName = "libvideoparse";
    private final static String pluginNameTemp = "libvideoparsetemp";
    private static String soPath = "";
    private SkyHttpDownloader task;
    private String MD5 = "";
    private String newVersion = "";
    private String downloadUrl = "";
    private int size = 0;
    private static final String tag = "plugin";

    public static void setContext(Context context) {
        mContext = context;
    }

    public static DownloadPlayerPlugin getInstance() {
        if (instance == null)
            instance = new DownloadPlayerPlugin();
        return instance;
    }

    private DownloadPlayerPlugin() {
        initPath();
    }

    public static void initPath() {
        soPath = mContext.getFilesDir() + "/lib/";
        // path = path.substring(0, path.lastIndexOf("/"));
        // LogUtils.d(path, "DownloadPlayerPlugin---path:"+path);
        // soPath = path + "/lib/";
        if (!new File(soPath).exists()) {
            new File(soPath).mkdir();
            LogUtils.d(tag, "LINUX_CMD_CHMOD---------");
            SkySystemUtil.execCmd(LINUX_CMD.LINUX_CMD_CHMOD, " -R 777 " + soPath);
        }
    }

    public static String getSOPath() {
        if (soPath.equals("")) {
            initPath();
        }
        return soPath;
    }

    public static String getSODefaultPath() {
        String path = mContext.getFilesDir() + "";
        int index = path.lastIndexOf("/");
        path = path.substring(0, index) + "/lib/";
        LogUtils.d("plugin", "DownloadPlayerPlugin---path:" + path);
        return path;
    }

    public boolean checkPluginLib(boolean isTianCiSystem, final SoFileBean soData) {
        LogUtils.d(tag, "checkPluginLib  isTianCiSystem:" + isTianCiSystem);
        if (isTianCiSystem) {
            return false;
        } else {
            task = new SkyHttpDownloader(DownloadPlayerPlugin.this);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    // //从后台获取更新插件的基本信息，包括 version ，url，md5
                    newVersion = soData.fileVersion;
                    downloadUrl = soData.fileUrl;
                    MD5 = soData.MD5;
                    size = soData.fileSize;
                    LogUtils.d(tag, "checkPluginLib---version:" + newVersion + " url:" + downloadUrl
                            + " md5:" + MD5 + " size:" + size);
                    if (!newVersion.equals("") && !downloadUrl.equals("") && !MD5.equals("")) {
                        startDownload(newVersion, downloadUrl);
                    } else {
                        LogUtils.d(tag, "get update data error!!!!");
                    }
                }
            }).start();
            return true;
        }

    }

    public void startDownload(String newVersion, final String downloadUrl) {
        String oldVersion = getOldVersion();
        if (Integer.parseInt(newVersion) > Integer.parseInt(oldVersion)) {
            new Thread() {
                public void run() {
                    LogUtils.d(tag, " start download url:" + downloadUrl + " name:" + pluginNameTemp
                            + " sopath:" + soPath);
                    task.setDownloadUrl(downloadUrl);
                    task.setDownloadFileName(pluginNameTemp);
                    task.setDownloadPath(soPath);
                    task.download();
                }
            }.start();
        } else {
            LogUtils.d(tag, " not need update plugin!! ");
        }
    }

    public String getOldVersion() {
        String version = "0";
        try {
            version = XServiceManager.getLiteConfigService().getStringValue("pluginversion", "0");
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return version;
    }

    public void savePluginVersion(String version) {
        try {
            XServiceManager.getLiteConfigService().saveStringConfig("pluginversion", version);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onStarted(String path) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFinished(String fileName) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, " DownloadPlayerPlugin  onFinished = " + fileName);
        try {
            String md5Str = MD5Util.getFileMD5String(new File(fileName));
            LogUtils.d(tag, "  onFinished md5Str =" + md5Str);
            if (MD5.toLowerCase().equals(md5Str)) {
                LogUtils.d(tag, "  onFinished  md5 equals md5Str");
                File file = new File(soPath + pluginName);
                if (file.exists())
                    file.delete();
                LogUtils.d(tag, " onFinished  LINUX_CMD_MV  Start");
                SkySystemUtil.execCmd(LINUX_CMD.LINUX_CMD_MV, soPath + pluginNameTemp + ".so  "
                        + soPath + pluginName + ".so");
                LogUtils.d(tag, "  onFinished  LINUX_CMD_MV  End");
                savePluginVersion(newVersion);
                LogUtils.d(tag, " DownLoadPlayerPlugin  Successed New Version = " + getOldVersion());
                task.deleteDownload();
            } else {
                LogUtils.d(tag, " need download again!!");
                task.deleteDownload();
                startDownload(newVersion, downloadUrl);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onFailed(String error) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, "  download failed!!  error:" + error);
    }

    @Override
    public void onDownloaded(float completedLen, float totalLen) {
        // TODO Auto-generated method stub
        // LogUtils.d(tag, "  downloaded !!");
    }

}
